import templateList from '@/config/templates'

const state = {
  examples: [],
  categories: [
    { key: 'all', name: '全部' },
    { key: 'vue', name: 'Vue.js' },
    { key: 'react', name: 'React' },
    { key: 'javascript', name: 'JavaScript' },
    { key: 'css', name: 'CSS' },
    { key: 'chart', name: '图表' },
    { key: 'animation', name: '动画' },
    { key: 'ui', name: 'UI组件' }
  ],
  selectedCategory: 'all',
  searchKeyword: '',
  favorites: [],
  recentExamples: []
}

const mutations = {
  SET_EXAMPLES(state, examples) {
    state.examples = examples
  },
  SET_SELECTED_CATEGORY(state, category) {
    state.selectedCategory = category
  },
  SET_SEARCH_KEYWORD(state, keyword) {
    state.searchKeyword = keyword
  },
  TOGGLE_FAVORITE(state, exampleId) {
    const index = state.favorites.indexOf(exampleId)
    if (index > -1) {
      state.favorites.splice(index, 1)
    } else {
      state.favorites.push(exampleId)
    }
  },
  ADD_RECENT_EXAMPLE(state, exampleId) {
    const index = state.recentExamples.indexOf(exampleId)
    if (index > -1) {
      state.recentExamples.splice(index, 1)
    }
    state.recentExamples.unshift(exampleId)
    if (state.recentExamples.length > 10) {
      state.recentExamples.pop()
    }
  }
}

const actions = {
  async loadExamples({ commit }) {
    const examples = convertTemplatesToExamples(templateList)
    commit('SET_EXAMPLES', examples)
  },
  
  loadExampleToEditor({ commit, rootState }, example) {
    // 将示例代码加载到编辑器
    commit('setCode', example.code, { root: true })
    commit('setCodeTitle', example.name, { root: true })
  },
  
  toggleFavorite({ commit }, exampleId) {
    commit('TOGGLE_FAVORITE', exampleId)
  },
  
  selectCategory({ commit }, category) {
    commit('SET_SELECTED_CATEGORY', category)
  },
  
  setSearchKeyword({ commit }, keyword) {
    commit('SET_SEARCH_KEYWORD', keyword)
  },
  
  addToRecent({ commit }, exampleId) {
    commit('ADD_RECENT_EXAMPLE', exampleId)
  }
}

const getters = {
  filteredExamples: (state) => {
    let examples = state.examples
    
    // 按分类筛选
    if (state.selectedCategory !== 'all') {
      examples = examples.filter(example => 
        example.category === state.selectedCategory
      )
    }
    
    // 按关键词搜索
    if (state.searchKeyword) {
      const keyword = state.searchKeyword.toLowerCase()
      examples = examples.filter(example =>
        example.name.toLowerCase().includes(keyword) ||
        example.description.toLowerCase().includes(keyword) ||
        example.tags.some(tag => tag.toLowerCase().includes(keyword))
      )
    }
    
    return examples
  },
  
  favoriteExamples: (state) => {
    return state.examples.filter(example => 
      state.favorites.includes(example.id)
    )
  },
  
  recentExamples: (state) => {
    return state.recentExamples.map(id => 
      state.examples.find(example => example.id === id)
    ).filter(Boolean)
  }
}

// 辅助函数
const convertTemplatesToExamples = (templates) => {
  return templates.map(template => {
    const category = inferCategory(template.name)
    const tags = generateTags(template)
    
    return {
      id: generateId(template.name),
      name: template.name,
      description: generateDescription(template),
      category,
      tags,
      icon: template.icon || '/favicon.ico',
      code: template.code,
      difficulty: inferDifficulty(template),
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      author: 'CodeRun Team',
      likes: 0,
      views: 0,
      isFavorite: false
    }
  })
}

const inferCategory = (name) => {
  const nameLower = name.toLowerCase()
  if (nameLower.includes('vue')) return 'vue'
  if (nameLower.includes('react')) return 'react'
  if (nameLower.includes('echarts') || nameLower.includes('chart')) return 'chart'
  if (nameLower.includes('animation') || nameLower.includes('animate')) return 'animation'
  if (nameLower.includes('css')) return 'css'
  if (nameLower.includes('element') || nameLower.includes('antd') || nameLower.includes('vant')) return 'ui'
  return 'javascript'
}

const generateTags = (template) => {
  const tags = []
  const nameLower = template.name.toLowerCase()
  
  if (nameLower.includes('vue')) tags.push('Vue')
  if (nameLower.includes('react')) tags.push('React')
  if (nameLower.includes('echarts')) tags.push('ECharts')
  if (nameLower.includes('element')) tags.push('Element Plus')
  if (nameLower.includes('animation')) tags.push('动画')
  if (nameLower.includes('chart')) tags.push('图表')
  if (nameLower.includes('css')) tags.push('CSS')
  
  return tags
}

const generateDescription = (template) => {
  // 根据模板名称生成描述
  const nameLower = template.name.toLowerCase()
  if (nameLower.includes('vue')) return 'Vue.js 示例代码'
  if (nameLower.includes('react')) return 'React 示例代码'
  if (nameLower.includes('echarts')) return 'ECharts 图表示例'
  if (nameLower.includes('element')) return 'Element Plus UI 组件示例'
  if (nameLower.includes('animation')) return 'CSS 动画效果示例'
  return 'JavaScript 示例代码'
}

const inferDifficulty = (template) => {
  // 根据代码复杂度推断难度
  const codeLength = JSON.stringify(template.code).length
  if (codeLength < 1000) return 'beginner'
  if (codeLength < 3000) return 'intermediate'
  return 'advanced'
}

const generateId = (name) => {
  return name.toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '')
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
} 